﻿import { useResizeObserver, useDebounceFn } from '@vueuse/core'
import router from '@/router'
const useSmartMenu = (systemConfig, headerMenu) => {
  const currentActivePosition = ref({
    left: 0,
    width: 0
  })
  const getActiveMenuPosition = () => {
    if (systemConfig.value.headerMenuStyle === 'smart' && (systemConfig.value.layout === 'horizontal' || systemConfig.value.layout === 'comprehensive' || systemConfig.value.layout === 'vertical__comprehensive')) {
      const parentDom = document.querySelector('.vk-header-center')
      const currentDom = document.querySelector('.vk-header-center .is-active')
      if (parentDom && currentDom) {
        const parentDomPosition = parentDom.getBoundingClientRect()
        const currentDomPosition = currentDom.getBoundingClientRect()
        currentActivePosition.value.left = currentDomPosition.left - parentDomPosition.left + 20
        currentActivePosition.value.width = currentDomPosition.width - 40
      }
    }
  }
  // 监听元素尺寸变化
  useResizeObserver(
    headerMenu,
    useDebounceFn(() => {
      getActiveMenuPosition()
    }, 300)
  )
  // 路由跳转后，当前选中项发生改变，选中线位置重新定位
  router.afterEach(() => {
    setTimeout(() => {
      getActiveMenuPosition()
    }, 300)
  })
  // 监听布局主题切换事件
  watch(
    () => systemConfig.value.layout,
    () => {
      if (systemConfig.value.headerMenuStyle === 'smart') {
        nextTick(() => {
          setTimeout(() => {
            getActiveMenuPosition()
          }, 300)
        })
      }
    }
  )
  // 监听顶栏菜单显示位置切换事件
  watch(
    () => systemConfig.value.headerMenuAlign,
    () => {
      if (systemConfig.value.headerMenuStyle === 'smart') {
        nextTick(() => {
          getActiveMenuPosition()
        })
      }
    }
  )
  // 监听顶栏菜单风格切换事件
  watch(
    () => systemConfig.value.headerMenuStyle,
    () => {
      if (systemConfig.value.headerMenuStyle === 'smart') {
        nextTick(() => {
          getActiveMenuPosition()
        })
      }
    }
  )
  onMounted(() => {
    nextTick(() => {
      setTimeout(() => {
        getActiveMenuPosition()
      }, 300)
    })
  })
  return {
    currentActivePosition
  }
}
export default useSmartMenu
